package cn.wx.autoconfiguration;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.wx.DefaultWxMaConfigFactory;
import cn.wx.WxMaConfigFactory;
import cn.wx.WxMaServiceRegisterPostProcessor;
import cn.wx.api.WxMaMultipleService;
import cn.wx.api.impl.WxMaMultipleServiceImpl;
import cn.wx.properties.MaProperties;
import cn.wx.properties.WxMaProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import static cn.wx.properties.WxMaProperties.PREFIX;

/**
 * 微信小程序自动装配类
 *
 * @author: sunshaoping
 * @date: Create by in 2:33 下午 2020/5/22
 */
@ConditionalOnClass(WxMaService.class)
@EnableConfigurationProperties(WxMaProperties.class)
@ConditionalOnProperty(prefix = PREFIX, value = "enabled", havingValue = "true", matchIfMissing = true)
public class WxMaAutoConfiguration {

    private final WxMaProperties properties;


    public WxMaAutoConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }


    @Bean
    @Primary
    @ConditionalOnMissingBean
    public WxMaMultipleService wxMaMultipleService() {
        return new WxMaMultipleServiceImpl(properties.getName());
    }


    @Bean
    @ConditionalOnMissingBean(name = "wxMaServiceRegisterPostProcessor")
    public WxMaServiceRegisterPostProcessor wxMaServiceRegisterPostProcessor(WxMaConfigFactory<MaProperties> wxMaConfigFactory) {
        return new WxMaServiceRegisterPostProcessor(properties, wxMaConfigFactory);
    }

    @Bean
    @ConditionalOnMissingBean
    public WxMaConfigFactory<MaProperties> wxMaConfigFactory() {
        return new DefaultWxMaConfigFactory();
    }
}
